package com.pers.springcloud.controller;

import com.pers.springcloud.entities.JSONResult;
import com.pers.springcloud.entities.Payment;
import com.pers.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @Author: 黄建
 * @Date: 2020/3/6 18:23
 */
@RestController
@Slf4j
@RequestMapping(value = "/payment")
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private PaymentService paymentService;

    @PostMapping(value = "/create")
    public JSONResult create(@RequestBody Payment payment) {
        Long aLong = paymentService.create(payment);
        if (aLong == 0) {
            return JSONResult.error("插入失败");
        }
        return JSONResult.success(serverPort, aLong);
    }

    @GetMapping(value = "/get/{id}")
    public JSONResult getPayment(@PathVariable(value = "id") Long id) {
        /*try {
            Thread.sleep(3000);
            System.out.println("sleep");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        Payment payment = paymentService.getPaymentById(id);
        return JSONResult.success(serverPort, payment);
    }

    @GetMapping(value = "/discovery", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String element : services
        ) {
            log.info("*****element:" + element);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances
        ) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/lb")
    public String getPaymentLb() {
        return serverPort;
    }

    @GetMapping("/zipkin")
    public String paymentZipkin()
    {
        return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }

}
